# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import time

from mindspore import context
import mindspore.nn as nn
from mindspore.train import Model
from mindspore.nn.metrics import Accuracy, F1
from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, \
    LossMonitor
from mindspore.train.serialization import save_checkpoint

from src.textrcnn import Net
from src.config import Config
from util import load_data, get_time_dif, get_args


def train_model(config, net, train_iter):
    start = time.time()
    print("============== Starting Training ==============")
    # 定义损失函数
    net_loss = SoftmaxCrossEntropyWithLogits()
    # 定义优化器
    net_opt = nn.Adam(net.trainable_params(),
                      learning_rate=config.learning_rate)

    config_ck = CheckpointConfig(save_checkpoint_steps=35,
                                 keep_checkpoint_max=10)
    ckpoint_cb = ModelCheckpoint(prefix='checkpoint_rcnn',
                                 directory=config.cb_path,
                                 config=config_ck)

    model = Model(net, net_loss, net_opt, metrics={'Accuracy': Accuracy(), 'F1': F1()})
    model.train(config.num_epochs, train_iter,
                callbacks=[ckpoint_cb, LossMonitor(per_print_times=30)], dataset_sink_mode=False)
    print("============== Training Down ==============")
    print('Time usage:{}s'.format(get_time_dif(start)))

    return model


def main():
    # 数据集地址
    dataset = get_args()

    # 配置文件
    config = Config(dataset)
    context.set_context(mode=context.GRAPH_MODE,
                        device_target=config.device)

    # 获取词汇表和数据
    vocab, train_iter, test_iter = load_data(config)

    # 设置词汇表的大小
    config.n_vocab = len(vocab)

    # 模型训练
    network = Net(config)
    model = train_model(config, network, train_iter)

    # 保存模型
    save_checkpoint(network, config.model_path)

    return model


if __name__ == '__main__':
    main()